import os
import time
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0"
}

def get_hotel_list(city_url):
    """
    获取城市酒店列表页中的酒店名与详情页链接
    """
    print(f"正在抓取城市页面：{city_url}")
    res = requests.get(city_url, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser')
    
    hotel_links = []
    for a in soup.select('a.hotel_name_link'):  # 携程页面可能需要更新这个选择器
        hotel_name = a.get_text(strip=True)
        hotel_link = 'https://hotels.ctrip.com' + a['href']
        hotel_links.append((hotel_name, hotel_link))

    print(f"共发现酒店数：{len(hotel_links)}")
    return hotel_links

def get_image_urls(hotel_url):
    """
    从酒店详情页中提取图片 JSON 接口，返回图片名与图片链接
    """
    try:
        hotel_id = hotel_url.split('/')[-1].split('.')[0]
        img_api = f"https://hotels.ctrip.com/webapi/hotel/imagealbum/{hotel_id}.json"

        res = requests.get(img_api, headers=headers)
        data = res.json()
        images = []

        for item in data.get('photos', []):
            url = item.get('url')
            title = item.get('title') or 'unknown'
            if url:
                images.append((title, url))
        return images
    except Exception as e:
        print(f"图片获取失败：{e}")
        return []

def save_images(city, hotel_name, images):
    """
    将图片保存到本地：酒店图片库/城市名/酒店名/*.jpg
    """
    folder = os.path.join('酒店图片库', city, hotel_name)
    os.makedirs(folder, exist_ok=True)

    for i, (title, url) in enumerate(images):
        ext = url.split('.')[-1].split('?')[0]
        file_name = f"{i+1}_{title[:20].strip().replace('/', '-')}.{ext}"
        file_path = os.path.join(folder, file_name)
        try:
            img_data = requests.get(url, timeout=10).content
            with open(file_path, 'wb') as f:
                f.write(img_data)
            print(f"✅ 成功保存：{file_path}")
        except Exception as e:
            print(f"❌ 下载失败：{url} 错误：{e}")
        time.sleep(0.2)  # 防封IP

def main():
    city = "北京"
    city_url = "https://hotels.ctrip.com/hotel/beijing1"  # 可以换成别的城市

    hotel_list = get_hotel_list(city_url)

    for hotel_name, hotel_url in hotel_list:
        print(f"\n🏨 正在处理酒店：{hotel_name}")
        image_list = get_image_urls(hotel_url)
        if image_list:
            save_images(city, hotel_name, image_list)
        else:
            print("⚠️ 无法获取图片")

if __name__ == "__main__":
    main()
